package essay

import (
	"html/template"
	"log"
	"net/http"

	essayTemplate "gitee.com/taadis/nook/template/essay"
)

func init() {
	log.Println("init /essay/ essay")
	http.HandleFunc("/essay/", essay)
}

//
func essay(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		getEssay(w, r)
	default:
		http.Error(w, "", http.StatusMethodNotAllowed)
	}
}

// 获取随笔
func getEssay(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
	id := query.Get("id")
	if id == "" {
		message := "随笔id没有值"
		log.Println(message)
		http.Error(w, message, http.StatusBadRequest)
		return
	}
	data, err := essayTemplate.Data(id)
	if err != nil {
		log.Print(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	filenames := []string{
		"template/root.tmpl",
		"template/essay.tmpl",
	}
	tmpl, err := template.ParseFiles(filenames...)
	if err != nil {
		log.Println(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	tmpl = template.Must(tmpl, err)
	err = tmpl.ExecuteTemplate(w, "root", data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
